//
//  MessageCell.m
//  ChatDemo
//
//  Created by 陈石 on 15/5/13.
//  Copyright (c) 2015年 陈石. All rights reserved.
//
#define ChatMargin 10    //间隔
#define ChatIconWH 44    //头像宽高height、width
#define ChatPicWH 200    //图片宽高
#define ChatContentW 180 //内容宽度

#define ChatTimeMarginW 15 //时间文本与边框间隔宽度方向
#define ChatTimeMarginH 10 //时间文本与边框间隔高度方向

#define ChatContentTop 15    //文本内容与按钮上边缘间隔
#define ChatContentLeft 25   //文本内容与按钮左边缘间隔
#define ChatContentBottom 15 //文本内容与按钮下边缘间隔
#define ChatContentRight 15  //文本内容与按钮右边缘间隔

#define ChatTimeFont [UIFont systemFontOfSize:11]    //时间字体
#define ChatContentFont [UIFont systemFontOfSize:14] //内容字体

#import "MessageCell.h"
#import "AudioPlayer.h"
#import "ImageAvatarBrowser.h"
#import "AppDelegate.h"
#import <SDWebImage/UIImageView+WebCache.h>

@interface MessageCell () <audioPlayerDelegate>
{
    BOOL contentVoiceIsPlaying;

    AVAudioPlayer *player;
    NSString      *voiceURL;
    UIView        *headImageBackView;

    AudioPlayer *audio;
    AppDelegate *appDelegate;
}
@end

@implementation MessageCell

- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];

    if (self)
    {

        self.backgroundColor = [UIColor clearColor];
        self.selectionStyle  = UITableViewCellSelectionStyleNone;

        // 1、创建时间
        self.labelTime               = [[UILabel alloc] init];
        self.labelTime.textAlignment = NSTextAlignmentCenter;
        self.labelTime.textColor     = [UIColor grayColor];
        self.labelTime.font          = ChatTimeFont;
        [self.contentView addSubview:self.labelTime];

        // 2、创建头像
        headImageBackView = [[UIView alloc] init];
        headImageBackView.layer.cornerRadius  = 22;
        headImageBackView.layer.borderWidth   = 0.9;
        headImageBackView.layer.masksToBounds = YES;
        headImageBackView.backgroundColor     = [[UIColor blackColor] colorWithAlphaComponent:0.4];
        [self.contentView addSubview:headImageBackView];
        self.btnHeadImage                     = [[UIImageView alloc] init];
        self.btnHeadImage.layer.cornerRadius  = 20;
        self.btnHeadImage.layer.masksToBounds = YES;
        [headImageBackView addSubview:self.btnHeadImage];

        // 3、创建头像下标
        self.labelNum               = [[UILabel alloc] init];
        self.labelNum.textColor     = [UIColor grayColor];
        self.labelNum.textAlignment = NSTextAlignmentCenter;
        self.labelNum.font          = ChatTimeFont;
        [self.contentView addSubview:self.labelNum];

        // 4、创建内容
        self.btnContent = [MessageContentButton buttonWithType:UIButtonTypeCustom];
        [self.btnContent setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        self.btnContent.titleLabel.font          = ChatContentFont;
        self.btnContent.titleLabel.numberOfLines = 0;

        [self.btnContent addTarget:self action:@selector(btnContentClick) forControlEvents:UIControlEventTouchUpInside];
        [self.contentView addSubview:self.btnContent];

        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(finish) name:@"VoicePlayHasInterrupt" object:nil];

        [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayAndRecord error:nil];
        contentVoiceIsPlaying = NO;
    }

    return self;
}

//cell的点击事件
- (void)btnContentClick
{
    //play audio
    if (self.messageFrame.message.type == MessageTypeVoice)
    {
        if (!contentVoiceIsPlaying)
        {
            [[NSNotificationCenter defaultCenter] postNotificationName:@"VoicePlayHasInterrupt" object:nil];
            contentVoiceIsPlaying = YES;
            audio                 = [AudioPlayer sharedInstance];
            audio.delegate = self;
            NSString *stringUrl = [NSString stringWithFormat:@"%@/%@", appDelegate.parameterManager.server, self.messageFrame.message.voiceURL];
            NSData   *songdata  = [NSData dataWithContentsOfURL:[NSURL URLWithString:stringUrl]];
            [audio playSongWithData:songdata];
        }
        else
        {
            [self finish];
        }
    }
        //show the picture
    else if (self.messageFrame.message.type == MessageTypePicture)
    {
        if (self.btnContent.backImageView)
        {
            [ImageAvatarBrowser showImage:self.btnContent.backImageView];
        }
        if ([self.delegate isKindOfClass:[UIViewController class]])
        {
            [[(UIViewController *) self.delegate view] endEditing:YES];
        }
    }
        // show text and gonna copy that
    else if (self.messageFrame.message.type == MessageTypeText)
    {
        [self.btnContent becomeFirstResponder];
        UIMenuController *menu = [UIMenuController sharedMenuController];
        [menu setTargetRect:self.btnContent.frame inView:self.btnContent.superview];
        [menu setMenuVisible:YES animated:YES];
    }
}

#pragma - mark avaudioDelegate

- (void)load
{
    [self.btnContent benginLoadVoice];
}

- (void)play
{
    //开启红外线感应
    [[UIDevice currentDevice] setProximityMonitoringEnabled:YES];
    [self.btnContent didLoadVoice];
}

- (void)finish
{
    //关闭红外线感应
    [[UIDevice currentDevice] setProximityMonitoringEnabled:NO];
    contentVoiceIsPlaying = NO;
    [self.btnContent stopPlay];
    [[AudioPlayer sharedInstance] stopSound];
}

//内容及Frame设置
- (void)setMessageFrame:(MessageFrame *)messageFrame
{
    appDelegate   = (AppDelegate *) [[UIApplication sharedApplication] delegate];
    _messageFrame = messageFrame;
    Message *message = messageFrame.message;

    // 1、设置时间
    self.labelTime.text  = message.strTime;
    self.labelTime.frame = messageFrame.timeF;

    // 2、设置头像
    headImageBackView.frame  = messageFrame.iconF;
    self.btnHeadImage.frame  = CGRectMake(2, 2, ChatIconWH - 4, ChatIconWH - 4);
    self.btnHeadImage.frame  = CGRectMake(2, 2, ChatIconWH - 4, ChatIconWH - 4);
    self.btnHeadImage.hidden = NO;
    if ([message.strIcon isEqualToString:@""])
    {
        self.btnHeadImage.image = [UIImage imageNamed:@"Avatar-Default.png"];
    }
    else
    {
        NSString *thumbnailURL = message.strIcon;
        NSString *url          = [NSString stringWithFormat:@"%@/%@", appDelegate.parameterManager.server, thumbnailURL];
        [self.btnHeadImage sd_setImageWithURL:[NSURL URLWithString:url]];
    }

    // 3、设置下标
    self.labelNum.text = message.strName;
    CGRect rect = messageFrame.iconF;
    rect.origin.y       = messageFrame.nameF.origin.y + 3;
    rect.size.height    = messageFrame.nameF.size.height;
    self.labelNum.frame = rect;

    // 4、设置内容

    //prepare for reuse
    [self.btnContent setTitle:@"" forState:UIControlStateNormal];
    self.btnContent.voiceBackView.hidden = YES;
    self.btnContent.backImageView.hidden = YES;

    self.btnContent.frame = messageFrame.contentF;

    if (message.from == MessageFromMe)
    {
        self.btnContent.isMyMessage = YES;
        [self.btnContent setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        self.btnContent.contentEdgeInsets = UIEdgeInsetsMake(ChatContentTop, ChatContentRight, ChatContentBottom, ChatContentLeft);
    }
    else
    {
        self.btnContent.isMyMessage = NO;
        [self.btnContent setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
        self.btnContent.contentEdgeInsets = UIEdgeInsetsMake(ChatContentTop, ChatContentLeft, ChatContentBottom, ChatContentRight);
    }

    //背景气泡图
    UIImage *normal;
    if (message.from == MessageFromMe)
    {
        normal = [UIImage imageNamed:@"chatto_bg_normal"];
        normal = [normal resizableImageWithCapInsets:UIEdgeInsetsMake(35, 10, 10, 22)];
    }
    else
    {
        normal = [UIImage imageNamed:@"chatfrom_bg_normal"];
        normal = [normal resizableImageWithCapInsets:UIEdgeInsetsMake(35, 22, 10, 10)];
    }

    [self.btnContent setBackgroundImage:normal forState:UIControlStateNormal];
    [self.btnContent setBackgroundImage:normal forState:UIControlStateHighlighted];

    switch (message.type)
    {
        case MessageTypeText:
            [self.btnContent setTitle:message.strContent forState:UIControlStateNormal];
            break;
        case MessageTypePicture:
        {
            self.btnContent.backImageView.hidden = NO;
            NSString *url = [NSString stringWithFormat:@"%@/%@", appDelegate.parameterManager.server, message.pictureURL];
            [self.btnContent.backImageView sd_setImageWithURL:[NSURL URLWithString:url]];

            self.btnContent.backImageView.frame = CGRectMake(0, 0, self.btnContent.frame.size.width, self.btnContent.frame.size.height);
            [self makeMaskView:self.btnContent.backImageView withImage:normal];
        }
            break;
        case MessageTypeVoice:
        {
            self.btnContent.voiceBackView.hidden = NO;
            if (message.from == MessageFromOther)
            {
                self.btnContent.voice.frame           = CGRectMake(0, 5, 20, 20);
                self.btnContent.voice.image           = [UIImage imageNamed:@"chat_animation3"];
                self.btnContent.voice.animationImages = [NSArray arrayWithObjects:[UIImage imageNamed:@"chat_animation1"], [UIImage imageNamed:@"chat_animation2"], [UIImage imageNamed:@"chat_animation3"], nil];
            }
            else
            {
                self.btnContent.voice.frame           = CGRectMake(80, 5, 20, 20);
                self.btnContent.voice.image           = [UIImage imageNamed:@"chat_animation_white3"];
                self.btnContent.voice.animationImages = [NSArray arrayWithObjects:[UIImage imageNamed:@"chat_animation_white1"], [UIImage imageNamed:@"chat_animation_white2"], [UIImage imageNamed:@"chat_animation_white3"], nil];
            }
        }
            break;
        case MessageTypeVideo:
        {
            self.btnContent.backImageView.hidden = NO;
            self.btnContent.backImageView.frame  = CGRectMake(0, 0, self.btnContent.frame.size.width, self.btnContent.frame.size.height);

            [self makeMaskView:self.btnContent.backImageView withImage:normal];
        }
        default:
            break;
    }
}

- (void)makeMaskView:(UIView *)view withImage:(UIImage *)image
{
    UIImageView *imageViewMask = [[UIImageView alloc] initWithImage:image];
    imageViewMask.frame = CGRectInset(view.frame, 0.0f, 0.0f);
    view.layer.mask     = imageViewMask.layer;
}

@end
